include (ExternalProject)

set_property (DIRECTORY PROPERTY EP_BASE Dependencies)

set (DEPENDENCIES)
set (EXTRA_CMAKE_ARGS)
set (proj protobuf)
list (APPEND DEPENDENCIES ${proj})

set(EP_SOURCE_DIR ${CMAKE_BINARY_DIR}/${proj})
set(EP_BINARY_DIR ${CMAKE_BINARY_DIR}/${proj}-build)
set(EP_INSTALL_DIR ${CMAKE_BINARY_DIR}/${proj}-install)

ExternalProject_Add(${proj}
    ${${proj}_EP_ARGS}
    GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
    GIT_TAG        66ed6dd75b0b5f0d62a9bf90509638f380cbcd7f
    SOURCE_DIR     ${EP_SOURCE_DIR}
    BINARY_DIR     ${EP_BINARY_DIR}
    INSTALL_DIR    ${EP_INSTALL_DIR}
    CMAKE_CACHE_ARGS
      #-DCMAKE_CXX_COMPILER:FILEPATH=${CMAKE_CXX_COMPILER}
      -DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER}
      #-DCMAKE_C_FLAGS:STRING=${ep_common_c_flags}
      -DCMAKE_DEBUG_POSTFIX:STRING=
      -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
  )

  #[[
list (APPEND EXTRA_CMAKE_ARGS
  -DBOOST_ROOT=${CMAKE_CURRENT_BINARY_DIR}/Dependencies/Source/ep_boost
  -DBoost_NO_SYSTEM_PATHS=ON)
]]

set(protobuf_DIR ${EP_INSTALL_DIR}/cmake)
set(absl_DIR ${EP_INSTALL_DIR}/lib/cmake/absl)
set(Protobuf_SRC_ROOT_FOLDER ${EP_SOURCE_DIR}/src)
set(PROTOBUF_INCLUDE_DIR ${EP_INSTALL_DIR}/include)

  if(WIN32)
    set(PROTOBUF_LIBRARIES ${EP_INSTALL_DIR}/lib/libprotobufd.lib)
    SET(Protobuf_PROTOC_EXECUTABLE ${EP_INSTALL_DIR}/bin/protoc.exe)
  else()
    set(PROTOBUF_LIBRARIES ${EP_INSTALL_DIR}/lib/libprotobuf.a)
  endif()
  message(status "SuperBuild PROTOBUF_LIBRARIES: ${PROTOBUF_LIBRARIES}")

  #set(PROTOBUF_LIBRARIES_DIR ${EP_INSTALL_DIR})

  list (APPEND EXTRA_CMAKE_ARGS
  -Dabsl_DIR:PATH=${absl_DIR}
  -Dprotobuf_DIR:PATH=${protobuf_DIR}
  -DPROTOBUF_INCLUDE_DIR:PATH=${PROTOBUF_INCLUDE_DIR}
  -DProtobuf_SRC_ROOT_FOLDER:PATH=${Protobuf_SRC_ROOT_FOLDER}
  -DPROTOBUF_LIBRARIES:FILEPATH=${PROTOBUF_LIBRARIES}
  -DProtobuf_PROTOC_EXECUTABLE:FILEPATH=${Protobuf_PROTOC_EXECUTABLE})

  #message(status "SuperBuild DPROTOBUF_LIBRARIES_DIR: ${PROTOBUF_LIBRARIES_DIR}")
  
# FIXME add to default target "all"?
ExternalProject_Add (Protobuf-demo
  DEPENDS ${DEPENDENCIES}
  SOURCE_DIR ${PROJECT_SOURCE_DIR}
  CMAKE_ARGS -DUSE_SUPERBUILD=OFF ${EXTRA_CMAKE_ARGS}
  INSTALL_COMMAND ""
  BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/Protobuf-demo-build)